package cn.hebutrun.oulabot.service.impl;


import cn.hebutrun.oulabot.common.Constants;
import cn.hebutrun.oulabot.common.util.TimeUtil;
import cn.hebutrun.oulabot.entity.BaseEntity;
import cn.hebutrun.oulabot.entity.LunchInfo;
import cn.hebutrun.oulabot.mapper.LunchInfoMapper;
import cn.hebutrun.oulabot.service.ILunchInfoService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.time.ZoneId;
import java.util.Date;
import java.util.List;

/**
 * 午餐信息表 服务实现类
 *
 * @author zhaolong
 * @since 2022-09-07
 */
@Service
public class LunchInfoServiceImpl extends ServiceImpl<LunchInfoMapper, LunchInfo>
    implements ILunchInfoService {

  @Override
  public List<LunchInfo> lunchInfo(String remoteAddr) {
    return this.list(
        Wrappers.lambdaQuery(LunchInfo.class)
            .eq(LunchInfo::getIp, remoteAddr)
            .last("limit 10")
            .orderByDesc(BaseEntity::getCreateTime));
  }

  @Override
  public String randomLunch() {
    return RandomUtil.randomEle(Constants.LUNCH);
  }

  @Override
  public String today(String remoteAddr) {
    String res;
    long count =
        this.count(
            Wrappers.lambdaQuery(LunchInfo.class)
                .eq(LunchInfo::getIp, remoteAddr)
                .ge(BaseEntity::getCreateTime, DateUtil.beginOfDay(new Date())));
    if (count == 0) {
      res = this.randomLunch();
      this.save(new LunchInfo().setIp(remoteAddr).setContent(res));
    } else {
      res =
          this.getOne(
                  Wrappers.lambdaQuery(LunchInfo.class)
                      .eq(LunchInfo::getIp, remoteAddr)
                      .orderByDesc(BaseEntity::getCreateTime)
                      .last("limit 1"))
              .getContent();
    }
    return res;
  }

  @Override
  public List<LunchInfo> lunchList(String qq) {
    this.today(qq);
    return this.list(
        Wrappers.lambdaQuery(LunchInfo.class)
            .select(LunchInfo::getContent, BaseEntity::getCreateTime)
            .eq(LunchInfo::getIp, qq)
            .orderByDesc(BaseEntity::getCreateTime)
            .last("limit 10"));
  }

  @Override
  public String lunchListInfo(String qq) {
    List<LunchInfo> lunchInfoList = this.lunchList(qq);
    StringBuilder sb = new StringBuilder();
    lunchInfoList.forEach(
        x ->
            sb.append(x.getContent())
                .append("   [")
                .append(LocalDateTimeUtil.format(x.getCreateTime(), "yyyy年MM月dd日"))
                .append("   ")
                .append(
                    TimeUtil.dayOfWeek(
                        Date.from(x.getCreateTime().atZone(ZoneId.systemDefault()).toInstant())))
                .append("]\n"));
    return sb.toString().trim();
  }
}
